package com.itmk.system.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itmk.config.redis.RedisUtils;
import com.itmk.constants.Constant;
import com.itmk.result.DataResult;
import com.itmk.system.common.entity.JsonData;
import com.itmk.system.common.service.RedisService;
import com.itmk.system.user.entity.SysUser;
import com.itmk.system.user.mapper.SysUserMapper;
import com.itmk.system.user.service.UserService;
import com.itmk.utils.PasswordEncoder;
import com.itmk.utils.PasswordUtils;
import com.itmk.utils.QRCodeUtils;
import com.itmk.utils.QiniuCloudUtil;
import com.itmk.vo.req.UserReqVO;
import com.itmk.vo.resp.UserInfoWithWechatInfoRespVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/api/user")
@Api(tags = "用户接口", description = "是所有用户接口的入口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private QiniuCloudUtil qiniuCloudUtil;



    @Autowired
    private RedisService redisService;

    @RequestMapping("needlogin")
    public JsonData needLogin() {

        return JsonData.buildSuccess("已登录", 0);

    }


    //查询用户列表
    @ApiOperation(value = "查询用户列表")
    @RequestMapping(value = "/getUserList", method = RequestMethod.POST)
    public DataResult getUserList(@RequestBody UserReqVO parm) {
//        QueryWrapper<SysUser> query  =new QueryWrapper<>();
//        if(StringUtils.isNotBlank(parm.getUsername())){
//            query.lambda().eq(SysUser::getUsername,parm.getUsername());
//        }
//        if(StringUtils.isNotBlank(parm.getMobile())){
//            query.lambda().eq(SysUser::getMobile,parm.getMobile());
//        }
        IPage<SysUser> page = new Page<>();
        page.setCurrent(parm.getCurrentPage());
        page.setSize(parm.getPageSize());
        IPage<SysUser> sysUsers = userService.getUserWithRoleList(page, parm);
        return DataResult.success(sysUsers);
    }

    /**
     * 新增用户
     *
     * @return
     */
    @ApiOperation(value = "新增用户")
    @RequiresPermissions("sys:user:add")
    @RequestMapping(value = "addUser", method = RequestMethod.POST)
    public DataResult addUser(@RequestBody SysUser user) {
        QueryWrapper<SysUser> query = new QueryWrapper<>();
        query.lambda().eq(SysUser::getUsername, user.getUsername());
        //查询用户是否存在
        SysUser one = userService.getOne(query);
        if (one != null) {
            return DataResult.getResult(300100, "用户名已经存在!");
        }
        String salt = RandomStringUtils.randomAlphanumeric(10);
        //加密用户密码
        String pwd = PasswordUtils.encode(user.getPassword(), salt);
        user.setPassword(pwd);
        user.setSalt(salt);
        boolean b = userService.save(user);
        if (b) {
            return DataResult.success();
        } else {
            return DataResult.getResult(300100, "新增用户失败");
        }
    }

    /**
     * 根据用户id查询用户端
     *
     * @return
     */
    @ApiOperation(value = "根据用户Id查询用户")
    @RequestMapping(value = "getUserById", method = RequestMethod.POST)
    public DataResult getUserById(@RequestBody SysUser user) {
        SysUser sysUser = userService.getById(user.getId());
        return DataResult.success(sysUser);
    }

    /**
     * 编辑用户保存
     *
     * @return
     */
    @ApiOperation(value = "编辑用户保存")
    @RequestMapping(value = "updateSaveUser", method = RequestMethod.POST)
    public DataResult updateSaveUser(@RequestBody SysUser user) {
        //判断用户是否存在
        QueryWrapper<SysUser> query = new QueryWrapper<>();
        query.lambda().eq(SysUser::getUsername, user.getUsername());
        SysUser one = userService.getOne(query);
        Long id = one.getId();//查询出来的id
        Long editId = user.getId();//编辑的用户id
        if (!id.equals(editId)) {
            return DataResult.getResult(300100, "用户不存在!");
        }
//        给密码加密
        user.setPassword(PasswordUtils.encode(user.getPassword(), one.getSalt()));
        boolean b = userService.updateById(user);
        if (b) {
            return DataResult.success();
        } else {
            return DataResult.getResult(300100, "编辑失败");
        }
    }

    @ApiOperation(value = "更新用户信息")
    @RequestMapping(value = "updateuserinfo", method = RequestMethod.POST)
    public DataResult updateUserInfo(@RequestBody SysUser user) {
        boolean b = userService.updateById(user);
        String redisKey = Constant.HOME_REDIS_KEY + "_" + user.getId().toString();
        log.info("更新用户信息{}", user);
        if (b) {
            this.redisService.delete(redisKey);
            return DataResult.success();
        } else {
            return DataResult.getResult(300100, "更新失败");
        }
    }

    /**
     * 根据用户id删除
     *
     * @return
     */
    @ApiOperation(value = "删除用户")
    @RequestMapping(value = "deleteUserById", method = RequestMethod.POST)
    public DataResult deleteUserById(@RequestBody SysUser user) {
        boolean b = userService.removeById(user.getId());
        if (b) {
            return DataResult.success();
        } else {
            return DataResult.getResult(300100, "删除用户失败");
        }
    }


    /**
     * 根据用户id查询信息并且要查询微信信息
     *
     * @return
     */
    @ApiOperation(value = "获取用户信息带上微信的信息")
    @RequestMapping(value = "getuserinfowithwechatinfo", method = RequestMethod.POST)
    public DataResult getUserInfoWithWechatInfo(@RequestBody Map<String, Object> userIdMap) {
        Integer userId = (Integer) userIdMap.get("userId");
        String redisKey = Constant.UserInfoWithWeChatInfo_REDIS_KEY + "_" + userId.toString();
        UserInfoWithWechatInfoRespVO userInfoWithWechatInfoRespVO = new UserInfoWithWechatInfoRespVO();
        if (redisService.hasKey(redisKey)) {
            log.info("读取缓存");
            userInfoWithWechatInfoRespVO = (UserInfoWithWechatInfoRespVO) RedisUtils.RedisToObject(redisService.get(redisKey).toString(), UserInfoWithWechatInfoRespVO.class);
        } else {
            userInfoWithWechatInfoRespVO = this.sysUserMapper.getUserInfoWithWechatInfo(userId);
            redisService.set(redisKey, userInfoWithWechatInfoRespVO, 1, TimeUnit.MINUTES);
        }
        return DataResult.success(userInfoWithWechatInfoRespVO);
    }


}
